<template>
    <div class="big-box">
        <div class="box">
            <head-img style="margin-left: 200px; margin-bottom: 20px"></head-img>
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="昵称" prop="name">
                    <el-input type="text" v-model="ruleForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="pass">
                    <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <div class="paywidth">
                        <el-dropdown @command="handleCommand2" class="type" >
                            <el-button type="info" style="background-color: #fff; color: #b4bccc; border: 1px solid #b4bccc">
                                {{sex}}<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="0">男生</el-dropdown-item>
                                <el-dropdown-item command="1">女生</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </el-form-item>
                <el-form-item label="生日" >
                    <div class="block">
                        <el-date-picker
                                v-model="value2"
                                type="date"
                                placeholder="选择日期"
                                format="yyyy 年 MM 月 dd 日"
                                value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </div>
                </el-form-item>

                <el-form-item label="验证码" prop="code" style="position: relative">
                    <el-input type="text" v-model="ruleForm.code" auto-complete="off" placeholder="请输入验证码" style="width: 150px; position: absolute; left: 0px;"></el-input>
                    <div @click="draw">
                        <v-sidentify style="display: inline-block; position: absolute; left: 170px" :identifyCode="codeImg"></v-sidentify>
                    </div>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber">
                    <el-input type="text" v-model="ruleForm.phoneNumber" autocomplete="off" ></el-input>

                </el-form-item>
                <el-form-item label="手机验证码" prop="phoneNumber">
                    <el-input type="text" v-model="ruleForm.phoneCode" autocomplete="off" style="width: 150px"></el-input>
                    <el-button type="primary" style="margin-left: 20px; width: 120px; text-align: center" @click="getPhoneCode" id="getCoder">获得验证码</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>

            </el-form>
        </div>
    </div>
</template>

<script>
    import DataItem from "./Data"
    import headImg from "./head-img"
    import Sidentify from "./SIdentify"
    import {request} from '../../network/request'

    export default {
        name: "register",
        data() {

            var checkAge = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('年龄不能为空'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if (value < 0 || value > 200) {
                            callback(new Error('不要乱输'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.ruleForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleForm.pass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var checkName = (rule, value, callback) => {
                value = value+'';
                if (value === '') {
                    callback(new Error('昵称不能为空'));
                }else if(value.length > 10){
                    callback(new Error('长度不能超过10'));

                }else{
                    callback();
                }
            };
            var checkPhoneNumber = (rule, value, callback) => {
                request({
                    url:"/checkPhone",
                    method: "post",
                    params:{
                        phoneNumber: this.ruleForm.phoneNumber,
                    }
                }).then(res=>{

                    if(res.data != true){
                        callback(new Error('手机号已经注册'));
                    }else {
                        callback();
                    }
                }).catch(err=>{
                    console.log(err);
                });
                var s = value + '';
                if (value === '') {
                    callback(new Error('手机号不能为空'));
                } else if(s.length != 11){
                    callback(new Error('请输入正确的手机号'));
                }
            };
            var checkCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('验证码不能为空'));
                }else {
                    callback();
                }
            };



            return {
                value2: '',
                sex:'性别',
                sexs:["男生", "女生"],
                ruleForm: {
                    pass: '',
                    checkPass: '',
                    age: '',
                    name: '',
                    phoneNumber:'',
                    code: '',
                    phoneCode:''

                },
                rules: {
                    pass: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPass: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    age: [
                        { validator: checkAge, trigger: 'blur' }
                    ],
                    name: [
                        { validator: checkName, trigger: 'blur' }
                    ],
                    phoneNumber:[
                        { validator: checkPhoneNumber, trigger: 'blur' }
                    ],
                    code:[
                        { validator: checkCode, trigger: 'blur' }
                    ]
                },
                codeImg:'',

                phoneCode: '',
            };
        },
        methods: {
            handleCommand2(command){
                this.sex = this.sexs[command];
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    //alert();
                    if (valid) {
                       // alert('submit!');

                        var s1= this.ruleForm.phoneCode + '';
                        var s2= this.phoneCode + '';
                        if(true){
                            this.$message({
                                message: '注册成功, 正在跳转...',
                                type: 'success'
                            });
                            request({
                                url:"/insertUser",
                                method: "post",
                                params:{
                                    phoneNumber: this.ruleForm.phoneNumber,
                                    passWord: this.ruleForm.pass,
                                    nickName: this.ruleForm.name,
                                    birthday:this.value2,
                                    sex:this.sex
                                }
                            }).then(res=>{


                                this.$router.replace("/login");

                            }).catch(err=>{
                                console.log(err);
                            });

                        }else{
                            this.$message.error('手机验证码错误');
                        }

                    } else {
                        //console.log('error submit!!');
                        this.$message.error('注册失败');
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            draw(){

                var sCode = "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
                var ans = "";
                for (var i = 0; i <= 3; i++){
                    var t = Math.floor(Math.random() * 10);
                    while(sCode[t] == ","){
                        var t = Math.floor(Math.random() * 100);
                    }

                    ans += sCode[t];
                }
                this.codeImg = ans;
            },
            getPhoneCode(qualifiedName, value){
                var s1 = this.codeImg.toLocaleLowerCase();
                var s2 = this.ruleForm.code.toLocaleLowerCase();
                if(s1 == s2){

                   // console.log(this.ruleForm.phoneNumber.length);
                    if(this.ruleForm.phoneNumber.length == 11){
                        var phoneCode = Math.ceil(Math.random() * 1000000);
                        this.phoneCode = phoneCode + '';
                        request({
                            url:"/register",
                            method: "post",
                            params:{
                                phoneNumber:this.ruleForm.phoneNumber,
                                code: phoneCode
                            }
                        }).then(res=>{

                        }).catch(err=>{
                            console.log(err);
                        });
                        this.$message({
                            message: '获得手机验证码成功',
                            type: 'success'
                        });
                        var btn = document.getElementById("getCoder");
                      // btn.setAttribute("disabled");
                        var cnt = 60;
                       // alert();
                       //btn.setAttributeNode('disabled');
                        btn.setAttribute('disabled', 'disabled');
                        var timer = setInterval(function () {
                            this.codeTime = --cnt + '';
                            btn.innerHTML = cnt + 's';
                            if(cnt == 0){
                                this.codeTime = "获得验证码";
                                btn.removeAttribute('disabled');
                                clearInterval(timer);
                                btn.innerHTML = '获得验证码';
                            }
                        }, 1000)
                    }else{
                        this.$message.error('请输入正确的手机号码');
                    }

                }
                else{
                    this.draw();
                    this.$message.error('图片验证码错误');
                }

            }

        },
        components:{
            "data-item":DataItem,
            "head-img": headImg,
            'v-sidentify':Sidentify
        },
        created() {
            this.draw();
        }

    }
</script>

<style scoped>
    .big-box{
        margin-top: 50px;
        width: 100%;
    }
    .box{
        width: 400px;
        margin: 0 auto;
    }
    .paywidth{
        width: 150px;
        display: inline-block;
        position: relative;
        left: 0px;
    }
</style>